package com.example.Words.room.model.storage.repository;
import android.content.Context;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import com.example.Words.room.model.Dao.WordDao;
import com.example.Words.room.model.entity.Word;
import com.example.Words.room.util.WordDatabaseUtil;

import java.util.List;
/**
 * <pre>
 *  author:huletian
 *  time    :2020/2/22
 *  desc    :数据仓库，包含数据库中取出的数据实体和对数据库的异步操作
 *  version:1.0
 * </pre>
 */

public class WordRepository {//数据仓库
    private WordDao wordDao;
    private  LiveData<List<Word>> getAllwords;
    public WordRepository(Context context) {
        WordDatabaseUtil wordDatabase=WordDatabaseUtil.getDatabase(context.getApplicationContext());
        wordDao=wordDatabase.getWordDao();
        getAllwords=wordDao.getAllwords();
    }
    public void insertWords(Word... words){
        new InsertAsyncTask(wordDao).execute(words);
    }
    public void updateWords(Word... words){
        new UpdateAsyncTask(wordDao).execute(words);
    }
    public void deleteWords(Word... words){
        new DeleteAsyncTask(wordDao).execute(words);
    }
    public void deleteAllWords(){
        new DeleteAllAsyncTask(wordDao).execute();
    }

    public LiveData<List<Word>> getAllWordsLive() {
        return getAllwords;
    }
    public LiveData<List<Word>> findWordsWithPatten(String patten){
        return wordDao.findWordWithPatten("%"+patten+"%");
    }
    static class InsertAsyncTask extends AsyncTask<Word,Void,Void> {
        private WordDao wordDao;
        public InsertAsyncTask(WordDao wordDao){
            this.wordDao=wordDao;
        }

        @Override
        protected Void doInBackground(Word... words) {
            wordDao.insertWords(words);
            return null;
        }
    }
    static class UpdateAsyncTask extends AsyncTask<Word,Void,Void>{
        private WordDao wordDao;
        public UpdateAsyncTask(WordDao wordDao){
            this.wordDao=wordDao;
        }

        @Override
        protected Void doInBackground(Word... words) {
            wordDao.updateWords(words);
            return null;
        }
    }
    static class DeleteAsyncTask extends AsyncTask<Word,Void,Void>{
        private WordDao wordDao;
        public DeleteAsyncTask(WordDao wordDao){
            this.wordDao=wordDao;
        }

        @Override
        protected Void doInBackground(Word... words) {
            wordDao.deleteWords(words);
            return null;
        }
    }
    static class DeleteAllAsyncTask extends AsyncTask<Void,Void,Void>{
        private WordDao wordDao;
        public DeleteAllAsyncTask(WordDao wordDao){
            this.wordDao=wordDao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            wordDao.deleteAllWords();
            return null;
        }
    }
}

